package com.handydata.antifraud.ws.dap;

import com.alibaba.fastjson.JSONObject;
import com.handydata.antifraud.annotation.Comment;
import com.handydata.antifraud.common.constant.DataSourceCode;
import com.handydata.antifraud.common.exception.WsInvokeException;
import com.handydata.antifraud.to.dap.BaiduAddressSwitchReqTO;
import com.handydata.antifraud.to.dap.BaiduAddressSwitchResTO;
import com.handydata.antifraud.util.DateUtil;
import com.handydata.antifraud.ws.WsInvocationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * 百度位置地址转换
 */
@Slf4j
@Service("baiduAddressSwitchService")
@Comment("百度位置地址转换")
public class BaiduAddressSwitchServiceImpl extends DataPlatformWsService<BaiduAddressSwitchReqTO, BaiduAddressSwitchResTO>
	implements WsInvocationService<BaiduAddressSwitchReqTO, BaiduAddressSwitchResTO> {

	@Override
	public BaiduAddressSwitchResTO query(BaiduAddressSwitchReqTO req) throws WsInvokeException {
		log.info("BaiduAddressSwitchReqTO {}",req);
		BaiduAddressSwitchResTO resTO = new BaiduAddressSwitchResTO();
		handleRequestParam(req);
		if (StringUtils.isEmpty(req.getAddress())) {
			log.error("参数校验 {}","address为空");
			resTO.setResCode("1111");
			resTO.setResMsg("百度位置地址转换接口参数address为空");
			return resTO;
		}
		this.dataType = DataSourceCode.BAIDU_ADDRESS_SWITCH.getCode();
		resTO = executeQuery(req);
		handleResponseParam(req, resTO);
		// 行内压测挡板处理
//		try {
//			Thread.sleep(250);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
//		resTO.setLocation("{\"lng\":121.55045460683195,\"lat\":31.227348292436346}");
//		resTO.setResCode("0000");
//		resTO.setResMsg("查询成功");
//		handleResponseParam(req, resTO);
//		// 挡板入库
//		DataCallLogsReqBO dataCallLogsReqBO = new DataCallLogsReqBO();
//		dataCallLogsReqBO.setId(UUID.randomUUID().toString().replace("-", ""));
//		dataCallLogsReqBO.setParams(JSONObject.toJSONString(req));
//		dataCallLogsReqBO.setElapsed(250);
//		dataCallLogsReqBO.setWselapsed(250);
//		dataCallLogsReqBO.setDataType(this.dataType);
//		dataCallLogsReqBO.setResCode("0000");
//		dataCallLogsReqBO.setResMsg("查询成功");
//		dataCallLogsReqBO.setResult("{\"lng\":121.55045460683195,\"lat\":31.227348292436346}");
//		dataCallLogsReqBO.setOrderId(req.getOrderId());
//		dataCallLogsReqBO.setUpdateTime(new Date());
//		dataCallLogsReqBO.setCreateTime(new Date());
//		dataCallLogsService.createDataCallLogs(dataCallLogsReqBO);
		return resTO;
	}
	
	@Override
	protected String createQueryXml(BaiduAddressSwitchReqTO req) {
		StringBuilder xml = new StringBuilder();
		xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
		xml.append("<subatm>");
		xml.append("<application>GwBiz.Req</application>");
		xml.append("<version>1.0.0</version>");
		xml.append("<sendTime>").append(DateUtil.now14()).append("</sendTime>");
		xml.append("<transCode>100078</transCode>");
		xml.append("<channelId>").append(encryInfo.getChannelId()).append("</channelId>");
		xml.append("<channelOrderId>").append(DateUtil.now17()).append("</channelOrderId>");
		xml.append("<address>").append(req.getAddress()).append("</address>");
		xml.append("<city>").append(req.getCity()).append("</city>");
		xml.append("<coordtype>").append(req.getCoordtype()).append("</coordtype>");
		xml.append("</subatm>");
		req.setQueryXml(xml.toString());
		return xml.toString();
	}
	
	@Override
	protected BaiduAddressSwitchResTO parseResultAndSave(String resultXml,	String orderId, Date createDate) {
		log.info("调用百度位置地址转换接口返回报文：{}", resultXml);
		BaiduAddressSwitchResTO resTO = new BaiduAddressSwitchResTO();
		try {
			// 解析xml，保存本地DB
			JSONObject jasonObject = JSONObject.parseObject(resultXml);
			if (null != jasonObject) {

				if ("0000".equals(jasonObject.get("resCode"))) {
					JSONObject resData=(JSONObject) jasonObject.get("resData");
//					resTO.setBdLongitudeAndLatitude(resData.getString("location"));
					resTO.setLocation(resData.getString("location"));
//					resTO.setPrecise(resData.getString("precise"));
//					resTO.setConfidence(resData.getString("confidence"));
//					resTO.setLevel(resData.getString("level"));
				} 
				//resTO.setReqId(dataCallLogsReqBO.getId());
				resTO.setResCode((String)jasonObject.get("resCode"));
				resTO.setResMsg((String)jasonObject.get("resMsg"));
			} else {
				resTO.setResCode("1111");
				resTO.setResMsg("百度位置地址转换口返回数据异常");
			}
		} catch (Exception e) {
			log.info("调用百度位置地址转换接口异常：{}", e.getMessage());
			resTO.setResCode("1111");
			resTO.setResMsg("调用百度位置地址转换接口异常");
		}
		log.info("调用百度位置地址转换接口返回结果：{}", JSONObject.toJSONString(resTO));
		return resTO;
	}
	
	@SuppressWarnings("unchecked")
	@PostConstruct
	@Override
	public void register() {
		registerToWsServiceFactory(this, BaiduAddressSwitchReqTO.class);
	}
	
	private void handleRequestParam(BaiduAddressSwitchReqTO req) {
		if (!StringUtils.isEmpty(req.getAttr())) {
			switch (req.getAttr()) {
				case "联系人手机号所在城市Gps":
					req.setAddress(req.getRelationPhoneCity());
					break;
				case "家庭住址城市GPS":
					req.setAddress(StringUtils.isEmpty(req.getProvince()) ? "" : req.getProvince().concat(StringUtils.isEmpty(req.getCity()) ? "" : req.getCity()));
					break;
				case "手机号所在城市Gps":
					req.setAddress(req.getPhoneCity());
					break;
				case "身份证所在城市Gps":
					req.setAddress(req.getArea());
					break;
				default:
					throw new IllegalStateException("Unexpected value: " + req.getAttr());
			}
		} else {
			if (StringUtils.isEmpty(req.getProvince()) && StringUtils.isEmpty(req.getCounty())) {
				req.setAddress("");
			} else {
				req.setAddress(req.getProvince().concat(req.getCity()).concat(req.getCounty()));
			}
		}
	}
	
	private void handleResponseParam(BaiduAddressSwitchReqTO req, BaiduAddressSwitchResTO res) {

		res.setHomeCityGps(req.getHomeCityGps());
		res.setIdCardCityGps(req.getIdCardCityGps());
		res.setPhoneCityGps(req.getPhoneCityGps());
		res.setRelationPhoneCityGps(req.getRelationPhoneCityGps());//从input 到req 到res再回到input，防止冲掉

		switch (req.getAttr()) {
			case "联系人手机号所在城市Gps":
				res.setRelationPhoneCityGps(res.getLocation());
				break;
			case "家庭住址城市GPS":
				res.setHomeCityGps(res.getLocation());
				break;
			case "手机号所在城市Gps":
				res.setPhoneCityGps(res.getLocation());
				break;
			case "身份证所在城市Gps":
				res.setIdCardCityGps(res.getLocation());
				break;
			default:
				throw new IllegalStateException("Unexpected value: " + req.getAttr());
		}
    }

}
